package net.chenlin.dp.modules.tcpDemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Yangsm
 * @ClassName: KeepAlive
 * @Description: TODO
 * @date 2022年11月10日 20:57
 */
public class KeepAlive implements Serializable {

    private static final long serialVersionUID = -2813120366138988480L;

    /* 覆盖该方法，仅用于测试使用。
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t维持连接包";

        //return "杨士民是个大帅哥";

    }

    public static void main(String[] args) throws IOException {
        // 定义服务器IP地址和端口号
        String serverIp = "139.9.159.254";
        int portNumber = 8090;

        try (Socket socket = new Socket(serverIp, portNumber)) {
            // 获取输入流和输出流对象
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            // 发送数据到服务器
            String messageToServer = "{JZCLIENT,20231218044850,REG,yangsm}";
            byte[] sendData = messageToServer.getBytes("UTF-8");
            outputStream.write(sendData);

            // 接收来自服务器的响应
            byte[] receiveData = new byte[1024];
            int bytesRead = inputStream.read(receiveData);
            String responseFromServer = new String(receiveData, 0, bytesRead, "UTF-8");
            System.out.println("Received from server: " + responseFromServer);

            // 关闭连接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
